package com.lczyfz.campusinfo.modules.frontuser.utils;


import com.lczyfz.campusinfo.common.utils.CacheUtils;
import com.lczyfz.campusinfo.common.utils.SpringContextHolder;
import com.lczyfz.campusinfo.modules.frontuser.dao.CampusinfoFrontUserDao;
import com.lczyfz.campusinfo.modules.frontuser.entity.CampusinfoFrontUser;
import com.lczyfz.campusinfo.modules.sys.dao.RoleDao;
import com.lczyfz.campusinfo.modules.sys.entity.Role;
import com.lczyfz.campusinfo.modules.sys.security.SystemAuthorizingRealm.Principal;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.subject.Subject;

/**
 * Created by yt on 2017/10/26.
 * 前端用户工具类
 */
public class FrontUserUtils {

    //TODO 前端用户DAO
    //前端用户DAO
    private static CampusinfoFrontUserDao campusinfoFrontUserDao = SpringContextHolder.getBean(CampusinfoFrontUserDao.class);
    private static RoleDao roleDao = SpringContextHolder.getBean(RoleDao.class);

    public static final String FRONTUSER_CACHE = "frontuserCache";
    public static final String USER_CACHE_ID_ = "id_";
    public static final String USER_CACHE_LOGIN_NAME_ = "ln";

    //TODO 根据前端登录名获取用户

    /**
     * 根据前端登录名获取用户
     *
     * @param loginName
     * @return 取不到返回null
     */

    public static CampusinfoFrontUser getByFrontLoginName(String loginName) {
        CampusinfoFrontUser campusinfoFrontUser = (CampusinfoFrontUser) CacheUtils.get(FRONTUSER_CACHE, USER_CACHE_LOGIN_NAME_ + loginName);
        if (campusinfoFrontUser == null) {
            campusinfoFrontUser = campusinfoFrontUserDao.getByFrontLoginName(new CampusinfoFrontUser(null, loginName));
            if (campusinfoFrontUser == null) {
                return null;
            }

            campusinfoFrontUser.setRoleList(roleDao.findList(new Role(campusinfoFrontUser)));
            CacheUtils.put(FRONTUSER_CACHE, USER_CACHE_ID_ + campusinfoFrontUser.getId(), campusinfoFrontUser);
            CacheUtils.put(FRONTUSER_CACHE, USER_CACHE_LOGIN_NAME_ + campusinfoFrontUser.getLoginName(), campusinfoFrontUser);
        }
        return campusinfoFrontUser;
    }

    //TODO 获取当前登录者对象

    /**
     * 获取当前登录者对象
     */
    public static Principal getPrincipal() {
        try {
            Subject subject = SecurityUtils.getSubject();
            Principal principal;
            principal = (Principal) subject.getPrincipal();
            if (principal != null) {
                return principal;
            }
//			subject.logout();
        } catch (UnavailableSecurityManagerException e) {

        } catch (InvalidSessionException e) {

        }
        return null;
    }
}
